package servlet;

import java.io.IOException;

import javax.servlet.ServletException;

import toolkit.Debug;
import validate.DateNotInPastValidator;
import validate.DatePickerValidator;
import validate.VisaCodeValidator;
import validate.VisaValidationCodeValidator;
import bean.MoneyBean;
import domain.entity.CreditCard;
import domain.entity.User;
import form.Form;
import form.element.TextInput;

public class MoneyServlet extends AbstractStepServlet
{
	private static final long serialVersionUID = 1L;
	
	private Form form;
	
	public MoneyServlet()
	{
		Debug.log("(" + id + ") MoneyServlet()");
	}
	
	@Override
	public void init()
			throws ServletException
	{
		super.init();
		
		form = new Form("money");
		
		TextInput code = new TextInput("code");
		code.setLabel("Creditcard code");
		code.setRequired();
		code.addValidator(new VisaCodeValidator());
		form.addChild(code);
		
		TextInput expirationDate = new TextInput("expirationDate");
		expirationDate.setLabel("Verval datum");
		expirationDate.setRequired();
		expirationDate.addValidator(new DatePickerValidator());
		expirationDate.addValidator(new DateNotInPastValidator());
		form.addChild(expirationDate);

		TextInput cvc = new TextInput("cvc");
		cvc.setLabel("Credit validation code");
		cvc.setRequired();
		cvc.addValidator(new VisaValidationCodeValidator());
		form.addChild(cvc);
	}
	
	@Override
	public void preDispatch()
	{
		super.preDispatch();
		
		form.clear();
	}
	
	@Override
	public void dispatchGet()
			throws ServletException, IOException
	{
		Debug.log("(" + id + ") MoneyServlet.dispatchGet()");
		
		User user = (User) session.getAttribute("user");
		
		CreditCard creditCard = user.getCreditCard();
		
		if (creditCard != null && method == "get")
		{
			form.populate(pizzaManager.getEntityValues(creditCard));
		}
		
		display();
	}
	
	@Override
	public void dispatchPost()
			throws ServletException, IOException
	{
		Debug.log("(" + id + ") MoneyServlet.dispatchPost()");
		
		MoneyBean bean = (MoneyBean) getPostValuesBean();

		if (bean != null)
		{
			form.populate(bean);
		}
		
		if (form.isValid())
		{
			User user = (User) session.getAttribute("user");
			
			CreditCard creditCard = user.getCreditCard();
			
			if (creditCard == null)
			{
				creditCard = new CreditCard();
				
				user.setCreditCard(creditCard);
			}
			
			pizzaManager.populateEntity(creditCard, form.getValues());
			
			session.setAttribute("user", user);
			
			redirectNextStep();
		}
		else
		{
			dispatchGet();
		}
	}
}
